//
//  CXommunityViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2019/1/4.
//  Copyright © 2019 xiaohan. All rights reserved.
//

#import "CXommunityViewController.h"
#import "XHSessionViewController.h"
#import "MineCommunityTableViewCell.h"
#import "XHomeSegementView.h"
#import "AllCommunityTableCell.h"
#import "ChatServer.h"
#import "XFoundSearchViewController.h"
#import "LoginViewController.h"
static NSString *const kCommunityTipSectionViewIdentifier = @"kCommunityTipSectionViewIdentifier";

@interface CXommunityViewController ()
@property (nonatomic,strong) ChatServer*chatServer;
@end

@implementation CXommunityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadMore:NO];
}

- (void)loadMore:(BOOL)isMore{
    if (!isMore) {
        if (kCurUser) {
            [self.chatServer getMyChatroomListCompletion:^(BOOL success, NSString * _Nonnull msg) {
                if (success) {
                    [self.tableView reloadData];
                }else{
                    [self.view makeToast:msg];
                }
            }];
        }
    }
    [self.chatServer getChatroomListIsMore:isMore completion:^(BOOL success, BOOL isHaveNextPage, NSString * _Nonnull msg) {
        [self endHeaderFooterRefreshingIsHaveNextPage:isHaveNextPage];
        if (success) {
            [self.tableView reloadData];
        }else{
            [self.view makeToast:msg];
        }
    }];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView.mj_header endRefreshing];
}
- (void)setupUI{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(AdaptedWidth(30), 0, kScreenWidth-2*AdaptedWidth(17), 44)];
    UILabel *tipLab = [[UILabel alloc]initWithFrame:titleView.bounds];
    tipLab.font = kBoldFont(24);
    tipLab.text = XLocalized(@"社群");
    [titleView addSubview:tipLab];
    self.navigationItem.titleView = titleView;
    [self addNavigationItemWithImageNames:@[@"search"] isLeft:NO target:self action:@selector(rightBtnClick) tags:nil];
    [self.tableView registerClass:XHomeTipHeadView.class forHeaderFooterViewReuseIdentifier:kCommunityTipSectionViewIdentifier];
    self.tableView.tableFooterView = [UIView new];
}

#pragma mark - action
- (void)rightBtnClick{
    XFoundSearchViewController *vc = [[XFoundSearchViewController alloc] initWithType:FoundSearchTypeGroup];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - table

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return self.chatServer.myChatList.count?1:0;
    }
    return self.chatServer.chatList.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        MineCommunityTableViewCell*cell = [MineCommunityTableViewCell cellForTableView:tableView];
        cell.data = self.chatServer.myChatList;
        kWeakSelf(self);
        cell.ClickBlock = ^(ChatroomModel* model) {
            if([[NIMSDK sharedSDK].teamManager isMyTeam:model.room_id]){
                XHSessionViewController *session = [[XHSessionViewController alloc]initWithSession:[NIMSession session:model.room_id type:NIMSessionTypeTeam]];
                [weakself.navigationController pushViewController:session animated:YES];
                return;
            }else{
                [self.view makeToast:@"你没在群里哦"];
            }
        };
        return cell;
    }else{
        AllCommunityTableCell *cell=[AllCommunityTableCell cellForTableView:tableView];
        cell.model = self.chatServer.chatList[indexPath.row];
        kWeakSelf(self);
        cell.jionBtnClickBlock = ^(ChatroomModel*model) {
            
            if([[NIMSDK sharedSDK].teamManager isMyTeam:model.room_id]){
                XHSessionViewController *session = [[XHSessionViewController alloc]initWithSession:[NIMSession session:model.room_id type:NIMSessionTypeTeam]];
                [weakself.navigationController pushViewController:session animated:YES];
                return;
            }
            [XAlertTool alertTitle:[NSString stringWithFormat:@"%@”%@“?",XLocalized(@"加入群聊"),model.name] message:nil cancelAction:^{
                
            } sureAction:^{
                [weakself.chatServer joinChatroom:model.room_id completion:^(BOOL success, NSString * _Nonnull msg) {
                    if (success) {
                        XHSessionViewController *session = [[XHSessionViewController alloc]initWithSession:[NIMSession session:model.room_id type:NIMSessionTypeTeam]];
                        [weakself.navigationController pushViewController:session animated:YES];
                    }else{
                        [weakself.view makeToast:msg];
                    }
                }];
            }];
        };
        return cell;
    }
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    XHomeTipHeadView *tipView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:kCommunityTipSectionViewIdentifier];
    tipView.titleLab.font = kBoldFont(16);
    if (section==0) {
        if (self.chatServer.myChatList.count) {
            tipView.titleLab.text = XLocalized(@"我的群聊");
        }else{
            tipView.titleLab.text = @"";
        }
    }else{
        tipView.titleLab.text = XLocalized(@"全部群聊");
    }
    return tipView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        if (self.chatServer.myChatList.count%2==0) {
            return self.chatServer.myChatList.count/2 * kCommunityClvCellHeight;
        }
        return kCommunityClvCellHeight*((self.chatServer.myChatList.count/2)+1);
    }else{
        return kCommunityClvCellHeight;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return self.chatServer.myChatList.count?AdaptedWidth(50):0.01f;
    }
    return AdaptedWidth(50);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==1) {
        if ([self.chatServer.chatList objectAtIndex:indexPath.row].is_join) {
            if([[NIMSDK sharedSDK].teamManager isMyTeam:[self.chatServer.chatList objectAtIndex:indexPath.row].room_id]){
                XHSessionViewController *session = [[XHSessionViewController alloc]initWithSession:[NIMSession session:[self.chatServer.chatList objectAtIndex:indexPath.row].room_id type:NIMSessionTypeTeam]];
                [self.navigationController pushViewController:session animated:YES];
                return;
            }else{
                [self.view makeToast:@"你没在群里哦"];
            }
        }
    }
}
#pragma - mark getter
- (ChatServer*)chatServer{
    if (!_chatServer) {
        _chatServer = [ChatServer new];
    }
    return _chatServer;
}
@end
